package cn.fl.insurance.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.Pager;
import cmm.user.facade.system.api.ISysOrgApiService;
import cmm.user.facade.system.dto.SysOrgDTO;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.insurance.condition.InsPlcBscInfoQueryCondition;
import cn.fl.insurance.condition.InsPlcStlQueryCondition;
import cn.fl.insurance.constant.InsuranceConstant;
import cn.fl.insurance.dto.InsPlcBscInfoDTO;
import cn.fl.insurance.dto.InsPlcStlDTO;
import cn.fl.insurance.service.IInsPlcBscInfoApiService;
import cn.fl.insurance.service.IInsPlcStlApiService;
import cn.fl.insurance.service.IInsPlcStlService;
import cn.fl.insurance.transform.InsPlcBscInfoVOTransform;
import cn.fl.insurance.transform.InsPlcStlVOTransform;
import cn.fl.insurance.vo.InsPlcBscInfoVO;
import cn.fl.insurance.vo.InsPlcStlVO;

/**
 * @Description: 保单结算表 客户端服务层接口实现
 * 业务层方法名称前缀：
 * 新增：add*
 * 删除：remove*
 * 修改：modify*
 * 批量：batch*
 * 查询对象：select* get*
 * 查询集合：search*
 */
@Service
public class InsPlcStlServiceImpl implements IInsPlcStlService {

    /**
     * 日志
     */
    @SuppressWarnings("unused")
    private static final Logger logger = LoggerFactory.getLogger(InsPlcStlServiceImpl.class);

    /**
     * TODO 自定义 API 暴露服务
     */
    @Autowired
    private IInsPlcStlApiService insPlcStlApiService;
    @Autowired
    private IInsPlcBscInfoApiService insPlcBscInfoApiService;
    @Autowired
    private ISysOrgApiService sysOrgApiService;
    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;

    @Override
    public InsPlcStlVO selectById(Long id) throws BaseException {
        if (StringUtils.isEmpty(id)) return null;
        InsPlcStlDTO dto = this.insPlcStlApiService.selectInsPlcStlById(id);
        return InsPlcStlVOTransform.toVO(dto);
    }

    @Override
    public Long add(InsPlcStlVO entity) throws BaseException {
        if (null == entity) return null;
        return this.insPlcStlApiService.addInsPlcStl(InsPlcStlVOTransform.toDTO(entity));
    }
    
    /**
     * 保单结算
     *
     * @param ids 保单号集合
     * @return
     */
    @Override
    public Boolean addPlcStl(List<Long> ids) throws BaseException{
    	if (null == ids) return false;
    	return this.insPlcStlApiService.addPlcStl(ids,CurrentThreadContext.getCurrentUserId(),new Date());
    }

    @Override
    public boolean removeByIds(List<Long> ids) throws BaseException {
        if (CollectionUtils.isEmpty(ids)) return false;
        return this.insPlcStlApiService.removeInsPlcStlByIds(ids, CurrentThreadContext.getCurrentUserId());
    }

    @Override
    public boolean modify(InsPlcStlVO entity) throws BaseException {
        if (null == entity) return false;
        return this.insPlcStlApiService.modifyInsPlcStl(InsPlcStlVOTransform.toDTO(entity));
    }

    /**
     * 结算管理列表
     * @param page
     * @return
     * @throws BaseException
     */
    @Override
    public Pager searchStlListPage(Pager page) throws BaseException {
        if (null == page) page = new Pager();
        page=this.insPlcBscInfoApiService.searchInsPlcStlListPage(page, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
        if(CollectionUtils.isNotEmpty(page.getResultList())){
            List<InsPlcBscInfoVO> voList=InsPlcBscInfoVOTransform.toVOList((List<InsPlcBscInfoDTO>) page.getResultList());
            this.setPlcOrgNm(voList,false);
            page.setResultList(voList);
        }
        return page;
    }

    /**
     * 设置组织架构信息
     * @param voList
     * @param flag 是否需要加载省公司\分公司
     */
    private void setPlcOrgNm(List<InsPlcBscInfoVO> voList,boolean flag){
        if(CollectionUtils.isEmpty(voList)){
            return;
        }
        //查询组织架构  查询所有组织架构 待优化
        List<SysOrgDTO> orgList=sysOrgApiService.searchSysOrgListBy(CurrentThreadContext.getCurrentSysCd());
        Map<String,String> orgMap=new HashMap<>(orgList.size());
        for (SysOrgDTO org:orgList) {
            orgMap.put(org.getOrgCd(),org.getOrgDispNm());
        }
        orgList=null;
        for(InsPlcBscInfoVO vo:voList){
            if(flag){//加载所属事业部、省公司、分公司
                if(CollectionUtils.isMapNotEmpty(orgMap)&&orgMap.containsKey(vo.getBuOrgCd())){
                    vo.setBuOrgCdNm(orgMap.get(vo.getBuOrgCd()));
                }
                if(vo.getCstMgrOrgCd().length()>=16){
                    if(CollectionUtils.isMapNotEmpty(orgMap)&&orgMap.containsKey(vo.getCstMgrOrgCd())){
                        vo.setCyOrgCdNm(orgMap.get(vo.getCstMgrOrgCd()));
                    }
                    if(CollectionUtils.isMapNotEmpty(orgMap)&&orgMap.containsKey(vo.getCstMgrOrgCd().substring(0,12))){
                        vo.setPrOrgCdNm(orgMap.get(vo.getCstMgrOrgCd().substring(0,12)));
                    }
                }else if(vo.getCstMgrOrgCd().length()>=12){
                    if(CollectionUtils.isMapNotEmpty(orgMap)&&orgMap.containsKey(vo.getCstMgrOrgCd())){
                        vo.setPrOrgCdNm(orgMap.get(vo.getCstMgrOrgCd()));
                    }
                }
            }else{
                if(CollectionUtils.isMapNotEmpty(orgMap)&&orgMap.containsKey(vo.getCstMgrOrgCd())){
                    vo.setBuOrgCdNm(orgMap.get(vo.getCstMgrOrgCd()));
                }
            }
        }
        orgMap=null;
    }

    /**
     * 结算记录管理列表
     * @param page
     * @return
     * @throws BaseException
     */
    @Override
    public Pager searchListPage(Pager page) throws BaseException {
        if (null == page) page = new Pager();
        page=this.insPlcStlApiService.searchInsPlcStlListPage(page, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
        if (CollectionUtils.isNotEmpty(page.getResultList())) {
            List<InsPlcStlVO> voList = InsPlcStlVOTransform.toVOList((List<InsPlcStlDTO>) page.getResultList());
            this.setDictData(voList);
            page.setResultList(voList);
        }
        return page;
    }

    private void setDictData(List<InsPlcStlVO> voList){
        Map<String, String> stlStsCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), InsuranceConstant.CODE_INS_PLC_STL_STS_CD);
        for (InsPlcStlVO vo : voList) {
            if(CollectionUtils.isMapNotEmpty(stlStsCdMap)&&stlStsCdMap.containsKey(vo.getStlStsCd())){
                vo.setStlStsCdNm(stlStsCdMap.get(vo.getStlStsCd()));
            }
        }
    }

    @Override
    public List<InsPlcStlVO> searchList(InsPlcStlQueryCondition condition) throws BaseException {
        return InsPlcStlVOTransform.toVOList(this.insPlcStlApiService.searchInsPlcStlList(condition));
    }

    /**
     * 导出结算清单
     *
     * @param condition
     * @return
     * @throws BaseException
     */
    @Override
    public List<InsPlcBscInfoDTO> searchExportStlList(InsPlcBscInfoQueryCondition condition) throws BaseException{
        if(null!=condition){
            condition.setSysCd(CurrentThreadContext.getCurrentSysCd());
            condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
        }
        return this.insPlcBscInfoApiService.searchExportStlList(condition);
    }

    /**
     * 查询结算汇总金额  保费总金额、结算总金额
     * @return
     * @throws BaseException
     */
    public DataResultVO getTtlStlAmt(InsPlcBscInfoQueryCondition condition) throws BaseException{
        DataResultDTO rst=this.insPlcBscInfoApiService.getTtlStlAmt(condition);
        DataResultVO vo=null;
        if(null==rst){
            vo=new DataResultVO(BaseConstant.IS_YESNO_NO);
        }else{
            vo=new DataResultVO(Integer.parseInt(rst.getCode()));
            vo.setData(rst.getData());
        }
        return vo;
    }

    /**
     * 导出保单结算数据
     * @param condition
     * @return 导出文件路径
     * @throws BaseException
     */
    public DataResultVO exportPlcStlList(InsPlcBscInfoQueryCondition condition) throws BaseException{
        if(null==condition){
            condition=new InsPlcBscInfoQueryCondition();
        }
        condition.setSysCd(CurrentThreadContext.getCurrentSysCd());
        condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
        DataResultDTO rst=this.insPlcStlApiService.exportPlcStlList(condition);
        if(null!=rst){
            return new DataResultVO(BaseConstant.IS_YESNO_YES,"导出完成",rst.getData());
        }else{
            return new DataResultVO(BaseConstant.IS_YESNO_NO,"导出失败");
        }
    }

    /**
     * 导出保单结算记录数据
     * @param condition
     * @return 导出文件路径
     * @throws BaseException
     */
    public DataResultVO exportPlcStlRecList(InsPlcBscInfoQueryCondition condition) throws BaseException{
        if(null==condition){
            condition=new InsPlcBscInfoQueryCondition();
        }
        condition.setSysCd(CurrentThreadContext.getCurrentSysCd());
        condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());

        DataResultDTO rst=this.insPlcStlApiService.exportPlcStlRecList(condition);
        if(null!=rst){
            return new DataResultVO(BaseConstant.IS_YESNO_YES,"导出完成",rst.getData());
        }else{
            return new DataResultVO(BaseConstant.IS_YESNO_NO,"导出失败");
        }
    }

}
